package com.music.muisc.controllers;

import com.music.muisc.dao.ForumRepository;
import com.music.muisc.entity.Forum;
import com.music.muisc.services.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
@RequestMapping("forums")
public class ForumController {

    @Autowired
    ForumService forumService;

    @Autowired
    ForumRepository forumRepository;

    @GetMapping
    public String displayForums(Model model){

        List<Forum> forums = forumService.getAll();
        model.addAttribute("forums", forums);
        return "forums/list-forums";
    }

    @GetMapping("/new")
    public String displayForumForm(Model model){

        Forum aForum = new Forum();
        model.addAttribute("forum",aForum);
        return "forums/new-forum";
    }

    @PostMapping("/save")
    public String createForum(Model model, Forum forum){

        forumRepository.save(forum);

        return "redirect:/forums";
    }
    @GetMapping("/update")
    public String displayForumUpdateForm(@RequestParam("id") int theId, Model model) {
        Forum theForum = forumService.findByBlogId(theId);
        model.addAttribute("forum", theForum);

        return "forums/new-forum";
    }
    @GetMapping("/delete")
    public String deleteForum(@RequestParam("id") int theId, Model model){
        Forum theForum = forumService.findByBlogId(theId);
        forumService.delete(theForum);
        return "redirect:/forums";
    }
}
